package com.pucong.gitee.database.backup.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pucong.gitee.database.backup.common.entity.sys.UserJwt;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserRequest {

    /**
     * 获取当前登录用户
     * @return
     */
    public static UserJwt getLoginUser() {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String lssoUserJson = (String) request.getAttribute(SystemConstant.REQUEST_USER_GET_NAME);
        ObjectMapper objectMapper = new ObjectMapper();
        UserJwt loginUser = null;
        try {
            loginUser = objectMapper.readValue(lssoUserJson, UserJwt.class);
        } catch (JsonProcessingException e) {
            throw new BusinessException("获取登录用户对象异常");
        }

        if (loginUser == null) {
            if (!ApplicationContextUtil.isDev()) {
                return null;
            } else {
                UserJwt userJwt = new UserJwt();
                userJwt.setUuid("1");
                userJwt.setUserName("超级管理员");
                userJwt.setLoginName("superadmin");
                return userJwt;
            }
        } else {
            return loginUser;
        }
    }
}
